package indi.h.security.signature;

import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;

public class VerifyImp implements Verify {
	private Signature signature;
	private String algorithm;

	protected VerifyImp(Signature signature, String algorithm) {
		// TODO Auto-generated constructor stub
		this.algorithm = algorithm;
		this.signature = signature;
	}

	public static Verify getInstance(String algorithm, String signAlgorithm) {
		try {
			return new VerifyImp(Signature.getInstance(signAlgorithm), algorithm);
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public static Verify getInstance(String algorithm, String signAlgorithm, byte[] publicKey) {
		try {
			Verify v = new VerifyImp(Signature.getInstance(signAlgorithm), algorithm);
			v.putUpPublicKey(publicKey);
			return v;
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public boolean verify(byte[] data, byte[] sign) {
		// TODO Auto-generated method stub
		try {
			signature.update(data);
			return signature.verify(sign);
		} catch (SignatureException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public void putUpPublicKey(byte[] key) {
		// TODO Auto-generated method stub
		try {
			X509EncodedKeySpec keySpec = new X509EncodedKeySpec(key);
			KeyFactory kf = KeyFactory.getInstance(algorithm);
			PublicKey publicKey = kf.generatePublic(keySpec);
			signature.initVerify(publicKey);
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
